//引入样式
require("../../assets/css/normalize.css");
require("../../assets/css/reset.css");
require("../../assets/fonts/iconfont.css");
require("../../assets/css/common.css");
require("./sports_riding.less");

//引入模块
const date = require("../../utils/date.js");
const dom = require("../../utils/dom.js");
const axios = require("../../utils/axios.js");

document.addEventListener("DOMContentLoaded", function () {
	//1. 地理定位
	/*
	AMap.plugin("AMap.Geolocation", function () {
		var geolocation = new AMap.Geolocation({
			// 是否使用高精度定位，默认：true
			enableHighAccuracy: true,
			// 设置定位超时时间，默认：无穷大
			timeout: 10000,
			// 定位按钮的停靠位置的偏移量
			offset: [10, 20],
			//  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
			zoomToAccuracy: true,
			//  定位按钮的排放位置,  RB表示右下
			position: "RB",
		});
		geolocation.getCurrentPosition(function (status, result) {
			if (status == "complete") {
				console.log("定位成功", result);
			} else {
				console.log("定位失败");
			}
		});
	});
	*/
	//2. 计算距离
	var p1 = [104.065751, 30.657453];
	var p2 = [116.397455, 39.909187];
	var dis = AMap.GeometryUtil.distance(p1, p2);

	//3. 定时器模拟跑步数据
	let duration = 0; //持续时间
	let meter = 0; //总里程
	let calorie = 0; //卡路里
	let timer = null; //定时器标识

	//设置一个函数，用于启动定时器
	function start() {
		timer = setInterval(function () {
			//速度
			let speed = getRand(3, 7);
			dom.get("#speed").textContent = speed + "米/秒";

			//时间
			duration++;
			dom.get("#time").textContent = date.getHMS(duration);

			//里程
			meter += speed;
			dom.get("#mileageNum").textContent = (meter / 1000).toFixed(3);

			//卡路里
			calorie = 60 * (meter / 1000) * 1.036;
			dom.get("#calorie").textContent = calorie.toFixed(2);
		}, 100);
	}
	start();

	//获取两个整数之间的随机数
	function getRand(min, max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}

	//4. 暂停
	dom.get(".zanting").addEventListener("click", function () {
		dom.get(".zanting").style.display = "none";
		dom.get(".bofang").style.display = "block";
		dom.get(".end").style.display = "block";
		clearInterval(timer); //清除定时器标识，停止计时
	});

	//5. 继续
	dom.get(".bofang").addEventListener("click", function () {
		dom.get(".zanting").style.display = "block";
		dom.get(".bofang").style.display = "none";
		dom.get(".end").style.display = "none";
		start(); //继续执行定时器
	});

	//6. 结束
	dom.get(".end").addEventListener("click", function () {
		//发请求保存数据
		axios
			.post("/api/exercise/save", {
				type: 0,
				duration,
				calorie,
				meter,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					location.href = "sports_ride.html";
				}
			});
	});
});
